﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using FluentFTP;


namespace FTP_progress
{
    class FtpDownLoad
    {

        // FTP 连接参数
        public string FtpServerIp { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string FileExtensions { get; set; }
        public string LocalFolder { get; set; }
        public string RemoteFolder { get; set; }

        // UI 控件
        public ProgressBar ProgressBar { get; set; }
        public Label LabelPercentage { get; set; }
        public Label LabelStatus { get; set; }

        // 私有成员
        private AsyncFtpClient _ftpClient;
        private List<string> _validExtensions;
        private int _totalFiles;
        private int _downloadedFiles;

        public async Task DownloadAsync()
        {
            try
            {
                // 初始化扩展名列表
                InitializeExtensions();

                // 创建FTP客户端
                _ftpClient = new AsyncFtpClient(FtpServerIp, Username, Password);
                // _ftpClient = new FtpClient(FtpServerIp, Username, Password);
                _ftpClient.Config.ConnectTimeout = 10000;

                // 连接服务器
                UpdateStatus("正在连接FTP服务器...");
                //await _ftpClient.ConnectAsync();
                await _ftpClient.Connect();


                if (Directory.Exists(LocalFolder)) Directory.Delete(LocalFolder, true);//会把文件夹删除
                // 确保本地目录存在
                Directory.CreateDirectory(LocalFolder);


                // 递归获取文件列表
                UpdateStatus("正在扫描文件...");

                // var allFiles = await GetFilesRecursiveAsync("/");
                // var allFiles = await GetFilesRecursiveAsync("md:/ ");
                var allFiles = await GetFilesRecursiveAsync(RemoteFolder);
                _totalFiles = allFiles.Count;
                _downloadedFiles = 0;

                if (_totalFiles == 0)
                {
                    UpdateStatus("未找到匹配的文件");
                    return;
                }

                UpdateStatus($"找到 {_totalFiles} 个文件，开始下载...");
                UpdateProgress(0);

                // 下载所有文件
                foreach (var remoteFile in allFiles)
                {
                    await DownloadFileAsync(remoteFile);
                    UpdateProgress(0);
                }

                UpdateStatus("下载完成！");
            }
            catch (Exception ex)
            {
                UpdateStatus($"错误: {ex.Message}");
            }
            finally
            {
                if (_ftpClient != null && _ftpClient.IsConnected)
                {
                    // await _ftpClient.DisconnectAsync();
                    await _ftpClient.Disconnect();
                }
            }
        }

        private void InitializeExtensions()
        {
            _validExtensions = new List<string>();

            if (!string.IsNullOrWhiteSpace(FileExtensions))
            {
                _validExtensions = FileExtensions.Split('/')
                    .Select(ext => ext.Trim().ToLower())
                    .Where(ext => !string.IsNullOrEmpty(ext))
                    .ToList();

                // 确保扩展名以点开头
                for (int i = 0; i < _validExtensions.Count; i++)
                {
                    if (!_validExtensions[i].StartsWith("."))
                    {
                        _validExtensions[i] = "." + _validExtensions[i];
                    }
                }
            }
        }

        private async Task<List<string>> GetFilesRecursiveAsync(string remotePath)
        {
            var files = new List<string>();

            foreach (var item in await _ftpClient.GetListing(remotePath))
            {
                if (item.Type == FtpObjectType.File)
                {
                    // 检查文件扩展名
                    var ext = Path.GetExtension(item.Name).ToLower();
                    if (_validExtensions.Count == 0 || _validExtensions.Contains(ext))
                    {
                        files.Add(item.FullName);
                    }
                }
                else if (item.Type == FtpObjectType.Directory)
                {
                    // 递归处理子目录
                    files.AddRange(await GetFilesRecursiveAsync(item.FullName));
                }
            }

            return files;
        }


        private async Task DownloadFileAsync(string remoteFile)
        {
            try
            {
                // 更新状态
                UpdateStatus($"下载: {Path.GetFileName(remoteFile)}");

                // 获取本地路径
                string localPath = GetLocalPath(remoteFile);
                // string localPath = "D:BACKUP\\RL";

                // 确保本地目录存在
                string localDir = Path.GetDirectoryName(localPath);
                Directory.CreateDirectory(localDir);

                // 创建进度处理器
                var progress = new Progress<FtpProgress>(p =>
                {
                    if (p.Progress < 0) return;
                    UpdateProgress(p.Progress);
                });

                // 下载文件
                await _ftpClient.DownloadFile(localPath, remoteFile, FtpLocalExists.Overwrite,
                    FtpVerify.None, progress);

                // 更新下载计数
                _downloadedFiles++;
            }
            catch (Exception ex)
            {
                UpdateStatus($"下载失败: {remoteFile} - {ex.Message}");
            }
        }

        private string GetLocalPath(string remotePath)
        {
            // 移除开头的斜杠
            string relativePath = remotePath.TrimStart('/');

            // 替换路径分隔符为系统分隔符
            relativePath = relativePath.Replace('/', Path.DirectorySeparatorChar);
            //去掉：
            relativePath = relativePath.Replace(":", "");
            // 组合本地路径
            string a = Path.Combine(LocalFolder, relativePath);
            return Path.Combine(LocalFolder, relativePath);
        }

        private void UpdateProgress(double progress)
        {
            // 计算整体进度 (已下载文件数 + 当前文件进度)
            double overallProgress = ((_downloadedFiles * 100) + progress) / _totalFiles;
            int percent = (int)Math.Round(overallProgress);

            // 确保百分比在0-100范围内
            percent = Math.Max(0, Math.Min(100, percent));

            // 更新UI
            if (ProgressBar.InvokeRequired || LabelPercentage.InvokeRequired)
            {
                ProgressBar.Invoke(new Action(() => ProgressBar.Value = percent));
                LabelPercentage.Invoke(new Action(() => LabelPercentage.Text = $"{percent}%"));
            }
            else
            {
                ProgressBar.Value = percent;
                LabelPercentage.Text = $"{percent}%";
            }
        }

        private void UpdateStatus(string message)
        {
            if (LabelStatus.InvokeRequired)
            {
                LabelStatus.Invoke(new Action(() => LabelStatus.Text = message));
            }
            else
            {
                LabelStatus.Text = message;
            }
        }
    }



}
